package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudyDAO {

	public StudyDTO findOne(int id) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		StudyDTO dto = new StudyDTO();
		
		try{
			Class.forName("org.apache.derby.jdbc.ClientDriver");

			conn = DriverManager.getConnection("jdbc:derby://localhost:1527/studydb;create=true", "study", "1111");

			String sql;
			sql = "SELECT * FROM example WHERE id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
						
			ResultSet rs = pstmt.executeQuery();

			rs.next();
			int studyId = rs.getInt("id");
			String name = rs.getString("name");
			dto.setId(studyId);
			dto.setName(name);
					
			rs.close();
			pstmt.close();
			conn.close();
	
		}catch(SQLException se){
			se.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(pstmt!=null)
					pstmt.close();
			}catch(SQLException se2){
			}
			try{
				if(conn!=null)
					conn.close();
			}catch(SQLException se){
				se.printStackTrace();
			}
		}
		
		return dto;
	}
}
